﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;

using Microsoft.SharePoint;
using Microsoft.Office.DocumentManagement.DocumentSets;
using System.Net;
using System.Xml.Linq;
using System.Xml;

namespace ApproverTools
{
    public partial class Form1 : Form
    {

        #region Members

        DataTable _tbl = null;
        //string siteStr = @"http://sp.korablik.local/shops/";
        string siteStr = @"http://sp.korablik.local/shops/";
        //string siteStr = @"http://192.168.0.223/shops/";

        #endregion

        #region Constructors

        public Form1()
        {
            InitializeComponent();
        }

        #endregion

        #region global methods
        private void testToolStripMenuItem1_Click(object sender, EventArgs e)
        {
//            using (SPSite site = new SPSite(@"http://sp.korablik.local/shops/"))
//            {
//                using (SPWeb web = site.OpenWeb())
//                {
//                    SPList list = web.Lists["Первичные документы"];
//                    SPQuery q = new SPQuery();
//                    // <Query>
//                    q.Query =
//@"
//<Where>
//<Eq>
//<FieldRef Name='_x0421__x043e__x0441__x0442__x043e__x044f__x043d__x0438__x0435__x0020__x0443__x0442__x0432__x0435__x0440__x0436__x0434__x0435__x043d__x0438__x044f_' />
//<Value Type='Choice'>Ожидают утверждения</Value>
//</Eq>
//</Where>
//"; // </Query>
//                    SPListItemCollection items = list.GetItems(q);
//                    foreach (SPListItem item in items)
//                    {
//                        //item["Состояние утверждения"] = "Утвержден";
//                        //item.Update();
//                    }
//                }
//            }
        }
        private void выходИзПрограммыToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
        #endregion
        #region Refresh
        private void обновитьСписокНеутвержденныхДокументовСПорталаToolStripMenuItem_Click(object sender, EventArgs e)
        {

            Refresh_Click(null, null);

        }
        private void Refresh_Click(object sender, EventArgs e)
        {
            DataTable tbl = new DataTable("Первичные документы");
            Exception err = GetDataList_x32(ref tbl);
            if (err == null)
            {
                _tbl = tbl;
                if (_tbl != null && _tbl.Rows.Count >= 0)
                {
                    DataColumn col = new DataColumn("IsCheck", typeof(bool));
                    _tbl.Columns.Add(col);
                }

                if (_tbl != null && _tbl.Rows.Count >= 0)
                {
                    //gv.Columns[2].Visible = false;

                    gv.DataSource = _tbl;
                    gv.Columns[0].DisplayIndex = gv.Columns.Count - 1;
                    gv.Columns[gv.Columns.Count - 1].DisplayIndex = 0;
                    gv.Columns["_x0414__x0430__x0442__x0430__x0020__x0434__x043e__x043a__x0443__x043c__x0435__x043d__x0442__x0430_"].HeaderText = "Дата документа";
                    gv.Columns["_x041d__x043e__x043c__x0435__x0440__x0020__x043d__x0430__x043a__x043b__x0430__x0434__x043d__x043e__x0439_"].HeaderText = "Номер накладной";
                    gv.Columns["_x041c__x0430__x0433__x0430__x0437__x0438__x043d_"].HeaderText = "Магазины";
                    gv.Columns["_x041f__x043e__x0441__x0442__x0430__x0432__x0449__x0438__x043a_"].HeaderText = "Поставщик";
                    gv.Columns["_x0414__x0430__x0442__x0430__x0020__x043a__x043e__x043c__x043f__x043b__x0435__x043a__x0442__x0430_"].HeaderText = "Дата комплекта";
                    gv.Columns["Title"].HeaderText = "Номер";
                }
                else
                    gv.DataSource = null;

                gv.DataSource = _tbl;
            }
            else
                MessageBox.Show("Ошибка: " + err.Message);
        }
        #endregion
        #region bnt Check
        private void выбратьВсеToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_tbl != null)
            {
                foreach (DataRow r in _tbl.Rows)
                    r["IsCheck"] = true;
            }
        }
        private void снятьВыборСоВсехToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_tbl != null)
            {
                foreach (DataRow r in _tbl.Rows)
                    r["IsCheck"] = false;
            }
        }
        private void btnCheck_Click(object sender, EventArgs e)
        {
            выбратьВсеToolStripMenuItem_Click(null, null);
        }
        private void btnUnCheck_Click(object sender, EventArgs e)
        {
            снятьВыборСоВсехToolStripMenuItem_Click(null, null);
        }
        #endregion
        #region save
        private void btnSaveAll_Click(object sender, EventArgs e)
        {
            сохранитьВсеФайлыВыбранныхДокументовToolStripMenuItem_Click(null, null);
        }
        private void сохранитьВсеФайлыВыбранныхДокументовToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SPFilesSave_x32();
            // SPFilesSave_64();
        }
        #endregion

        #region Data

        private Exception GetDataList_x32(ref DataTable parTpl)
        {
            Exception ret = null;            
            List<string> errList = new List<string>();
            GetSP_PermDocs_ForApproverList(ref parTpl, ref errList);
            return ret;
        }
        private Exception GetDataList_x64(ref DataTable parTpl)
        {
            Exception ret = null;

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteStr))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {

                            //foreach (SPList lll in web.Lists)
                            //{
                            //}

                            SPDocumentLibrary lib = (SPDocumentLibrary)web.Lists["Первичные документы"];
                            SPQuery q = new SPQuery();
                            // <Query>
                            q.Query =
        @"
<Where>
<Eq>
<FieldRef Name='_x0421__x043e__x0441__x0442__x043e__x044f__x043d__x0438__x0435__x0020__x0443__x0442__x0432__x0435__x0440__x0436__x0434__x0435__x043d__x0438__x044f_' />
<Value Type='Choice'>Ожидают утверждения</Value>
</Eq>
</Where>
"; // </Query>
                            // <ViewFields>
                            q.ViewFields =
    @"
   <FieldRef Name='ID' />
   <FieldRef Name='_x0414__x0430__x0442__x0430__x0020__x0434__x043e__x043a__x0443__x043c__x0435__x043d__x0442__x0430_' />
   <FieldRef Name='_x041d__x043e__x043c__x0435__x0440__x0020__x043d__x0430__x043a__x043b__x0430__x0434__x043d__x043e__x0439_' />
   <FieldRef Name='_x041c__x0430__x0433__x0430__x0437__x0438__x043d_' />
   <FieldRef Name='_x041f__x043e__x0441__x0442__x0430__x0432__x0449__x0438__x043a_' />
   <FieldRef Name='_x0414__x0430__x0442__x0430__x0020__x043a__x043e__x043c__x043f__x043b__x0435__x043a__x0442__x0430_' />
   <FieldRef Name='Title' />
"; // </ViewFields>

                            SPListItemCollection items = lib.GetItems(q);
                            if (items.Count > 0)
                                _tbl = items.GetDataTable();

                            //foreach (SPListItem item in items)
                            //{

                            // item["Состояние утверждения"] = "Утвержден";
                            // item.Update();

                            //} // foreach

                        } // using SPWeb
                    } // using SPSite                    

                    if (_tbl != null && _tbl.Rows.Count <= 0 || _tbl == null)
                    {
                        string errMsg = "Нет документов! все документы согласованы";
                        ret = new Exception(errMsg);
                        gv.DataSource = null;
                        throw ret;
                    }

                });
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, ret);
            }
            return ret;
        }
        public Exception GetSP_PermDocs_ForApproverList(ref DataTable tbl, ref List<string> errList)
        {
            return Get(ref tbl, ref errList, @"http://sp.korablik.local:98/ws/SP/PermDocs_ForApproveList.aspx");
        }
        public Exception GetSP_PermDocs_FilesList_ByDocID(ref DataTable tbl, ref List<string> errList, int parId)
        {
            string urlStr = @"http://sp.korablik.local:98//ws/SP/PermDocs_FilesInfo_ByDocSetID.aspx";
            return Get_ByID(ref tbl, ref errList, urlStr, parId);
        }
        public Exception Get(ref DataTable tbl, ref List<string> errList, string UrlStr)
        {
            DateTime dt = DateTime.Now;
            dt = new DateTime(dt.Year, dt.Month, dt.Day);
            return Get(ref tbl, ref errList, UrlStr, dt.Year, dt.Month);
        }
        public Exception Get(ref DataTable tbl, ref List<string> errList, string UrlStr, int Year, int Month)
        {
            Exception ret = null;
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Headers["Cache-Control"] = "no-cache";
                wc.UseDefaultCredentials = false;
                wc.Credentials = new System.Net.NetworkCredential("anonymous", "janeDoe@contoso.com");
                wc.UseDefaultCredentials = false;

                string paramsStr = @"?guid=" + Guid.NewGuid().ToString()
                    + @"&year=" + Year.ToString()
                    + @"&month=" + Month.ToString();

                byte[] data = wc.DownloadData(UrlStr + paramsStr);
                // if (tbl == null)
                tbl = new DataTable();
                if (data.Length > 0)
                {
                    using (System.IO.MemoryStream xmlStream = new System.IO.MemoryStream())
                    {
                        xmlStream.Write(data, 0, data.Length);
                        xmlStream.Position = 0;
                        tbl.ReadXml(xmlStream);
                        xmlStream.Position = 0;
                        if (errList == null)
                            errList = new List<string>();
                        GetErrList(ref data, ref errList);
                        if (errList.Count > 0)
                            throw new Exception(errList[0]);
                    }
                }
                else
                    throw new Exception(@"Web Service http://sp.korablik.local не вернул данных");
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            return ret;
        }
        public Exception Get_ByID(ref DataTable tbl, ref List<string> errList, string UrlStr, int parID)
        {
            Exception ret = null;
            try
            {
                System.Net.WebClient wc = new System.Net.WebClient();
                wc.Headers["Cache-Control"] = "no-cache";
                wc.UseDefaultCredentials = false;
                wc.Credentials = new System.Net.NetworkCredential("anonymous", "janeDoe@contoso.com");
                wc.UseDefaultCredentials = false;

                string paramsStr = @"?guid=" + Guid.NewGuid().ToString()
                    + @"&intID=" + parID;

                byte[] data = wc.DownloadData(UrlStr + paramsStr);
                // if (tbl == null)
                tbl = new DataTable();
                if (data.Length > 0)
                {
                    using (System.IO.MemoryStream xmlStream = new System.IO.MemoryStream())
                    {
                        xmlStream.Write(data, 0, data.Length);
                        xmlStream.Position = 0;
                        tbl.ReadXml(xmlStream);
                        xmlStream.Position = 0;
                        if (errList == null)
                            errList = new List<string>();
                        GetErrList(ref data, ref errList);
                        if (errList.Count > 0)
                            throw new Exception(errList[0]);
                    }
                }
                else
                    throw new Exception(@"Web Service http://sp.korablik.local не вернул данных");
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            return ret;
        }
        public Exception GetErrList(ref byte[] parData, ref List<string> parErrList)
        {
            Exception ret = null;
            try
            {
                StringBuilder sb = new StringBuilder();
                foreach (byte bt in parData)
                    sb.Append((char)bt);
                string str = sb.ToString();
                XDocument xErrors = XDocument.Parse(str);
                var query = from g in xErrors.Descendants("Errors")
                            select new
                            {
                                errName = (string)g.Element("Err")
                            };
                foreach (var node in query)
                {
                    if (node.errName == null)
                    {
                        // Errors not found
                    }
                    else
                    {
                        parErrList.Add(node.errName);
                    }
                }
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            return ret;
        }

        #endregion

        #region files

        Exception SPFilesSave_64()
        {
            Exception ret = null;

            if (_tbl == null || _tbl.Rows.Count == 0)
                return ret;

            folderBrowserDialog1.Description =
@"Путь для сохраения файлов";
            folderBrowserDialog1.ShowNewFolderButton = true;
            //folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                string pathStr = folderBrowserDialog1.SelectedPath;
                int id = -1;

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(siteStr))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPDocumentLibrary lib = (SPDocumentLibrary)web.Lists["Первичные документы"];
                            SPQuery q = new SPQuery();
                            foreach (DataRow r in _tbl.Rows)
                            {
                                if (r["ID"] == DBNull.Value)
                                    continue;
                                id = (int)r["ID"];

                                //                                q.Query =
                                //    @"
                                //    <Where>
                                //    <Eq>
                                //    <FieldRef Name='ID' />
                                //    <Value Type='Counter'>" + id + @"</Value>
                                //    </Eq>
                                //    </Where>
                                //    ";
                                //                                //foreach(SPListItem folder in lib.Folders)
                                //                                //{
                                //                                //    SPFolder f = (SPFolder)folder.Folder;
                                //                                //    foreach (SPFile file in f.Files)
                                //                                //    {
                                //                                //        byte [] bytes = 
                                //                                //            file.OpenBinary(SPOpenBinaryOptions.SkipVirusScan);
                                //                                //    }
                                //                                //}

                                //                                SPListItemCollection items = lib.GetItems(q);
                                //                                foreach (SPListItem item in items)
                                //                                {
                                //                                }

                                SPDocumentLibrary DocLib = (SPDocumentLibrary)web.Lists[@"Первичные документы"];
                                SPListItem item = DocLib.GetItemById(id);
                                DocumentSet docset = DocumentSet.GetDocumentSet(item.Folder);
                                foreach (SPFile file in docset.Folder.Files)
                                {
                                    if (r["_x041c__x0430__x0433__x0430__x0437__x0438__x043d_"] == DBNull.Value)
                                        continue;

                                    string strTmp = (string)r["_x041c__x0430__x0433__x0430__x0437__x0438__x043d_"];
                                    int i = strTmp.IndexOf('|');
                                    string shopname = strTmp.Substring(0, i);
                                    string filename =
                                        @"C:\tmp\"
                                        + shopname
                                        + "_"
                                        + r["Title"]
                                        + "_"
                                        + file.Name;

                                    byte[] bytes = file.OpenBinary();

                                    using (FileStream filestream =
                                            File.Create(filename, 1024, FileOptions.None))
                                    {
                                        filestream.Write(bytes, 0, bytes.Length);
                                    }

                                    //using (Stream stream =
                                    //    file.OpenBinaryStream(SPOpenBinaryOptions.SkipVirusScan))
                                    //{
                                    //    using (FileStream filestream =
                                    //        File.Create(@"C:\tmp\" + file.Name, 1024, FileOptions.None))
                                    //    {

                                    //    }
                                    //}

                                    //using (StreamReader reader = new StreamReader(file.OpenBinaryStream()))
                                    //{
                                    //    string content = reader.ReadToEnd();
                                    //}

                                }
                            }
                        } // using spweb
                    } // using spsite
                });
            }

            return ret;
        }

        Exception SPFilesSave_x32()
        {

            Exception ret = null;

            if (_tbl == null || _tbl.Rows.Count == 0)
                return ret;

            folderBrowserDialog1.Description =
@"Путь для сохраения файлов";
            folderBrowserDialog1.ShowNewFolderButton = true;
            //folderBrowserDialog1.RootFolder = Environment.SpecialFolder.Personal;

            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                string pathStr = folderBrowserDialog1.SelectedPath;
                int id = -1;

                foreach (DataRow r in _tbl.Rows)
                {
                    if (r["ID"] == DBNull.Value)
                        continue;

                    if (r["IsCheck"] == DBNull.Value)
                        continue;

                    if ((bool)r["IsCheck"] == false)
                        continue;

                    id = (int)r["ID"]; // sample - 384940
                    DataTable tblTmp= new DataTable("tblTmp");
                    List<string> errList = new List<string>();
                    Exception err = GetSP_PermDocs_FilesList_ByDocID(ref tblTmp, ref errList, id);
                    if (err == null && tblTmp!=null)
                    {
                        foreach (DataRow rr in tblTmp.Rows)
                        {

                            string strTmp = (string)r["_x041c__x0430__x0433__x0430__x0437__x0438__x043d_"];
                            int i = strTmp.IndexOf('|');
                            string shopname = strTmp.Substring(0, i);
                            string filename =
                                @"C:\tmp\"
                                + shopname
                                + "_"
                                + r["Title"]
                                + "_"
                                + rr["FileName"];

                            /*
                            string filePathSrv =
    @"http://sp.korablik.local" + rr["ServerRelativeUrl"].ToString();

                            WebClient wc = new WebClient();
                            byte [] srvdata = wc.DownloadData(filePathSrv);
                            */

                            string filePathSrv =
    @"http://sp.korablik.local:98/ws/SP/PermDocs_FileData.aspx?intID=" + id + "&FileName=" + rr["FileName"];
                            WebClient wc = new WebClient();
                            byte[] srvdata = wc.DownloadData(filePathSrv);


                            //using (FileStream fsSrv = File.Open(filePathSrv, FileMode.Open))
                            //{
                            //    using (FileStream filestream =
                            //            File.Create(filename, 1024, FileOptions.None))
                            //    {
                            //        byte [] buf = new byte[1024];
                            //        int offset = 0;
                            //        int bytescount = -1;
                            //        do
                            //        {
                            //            bytescount = fsSrv.Read(buf, offset, 1024);
                            //            if (bytescount > 0)
                            //            {
                            //                filestream.Write(buf, offset, bytescount);
                            //                offset += bytescount;
                            //            }
                            //        } while (bytescount > 0);
                            //    }
                            //}

                            using (FileStream filestream =
                                File.Create(filename, 1024, FileOptions.None))
                            {
                                filestream.Write(srvdata, 0, srvdata.Length);
                            }

                        }
                    }

                }

            }

            return ret;
        }

        #endregion

    }
}
